import { useEffect, useState } from 'react'

/**
 * @param category 缓存的类别
 */
interface IUseStorage {
  category: string;
}

export interface IStorage {
  cache: Record<string, any>;
  addCategory: (category: string) => void;
  removeCategory: (category: string) => void;
  getCategory: (category: string) => Record<string, any>;
  getCache: (category: string, key: string) => Record<string, any> | undefined;
  removeCache: (category: string, key: string) => void;
  setCache: (category: string, key: string, value: any) => void;
}

export const useStorage = (props: IUseStorage) => {

  const { category } = props;

  /**
   * @description 添加类别
   * @param category 类别
   */
  const addCategory = (category: string) => {
    localStorage.setItem(category, '{}');
    setCurrentCache({});
  }

  /**
   * @description 删除类别
   * @param category 类别
   */
  const removeCategory = (category: string) => {
    localStorage.removeItem(category);
    setCurrentCache({});
  }

  /**
   * @description 获取类别
   * @param category 类别
   */
  const getCategory = (category: string) => {
    return JSON.parse(localStorage.getItem(category) || '{}');
  }

  /**
   * @description 获取对应类别的缓存值
   * @param category 类别
   * @param key 缓存值 Key 名
   */
  const getCache = (category: string, key: string) => {
    const cache = localStorage.getItem(category);
    return cache ? JSON.parse(cache)[key] : undefined;
  }

  /**
   * @description 删除对应类别的缓存值
   * @param category 类别
   * @param key 缓存值 Key 名
   */
  const removeCache = (category: string, key: string) => {
    const cache = JSON.parse(localStorage.getItem(category) || '{}');
    delete cache[key];
    localStorage.setItem(category, JSON.stringify(cache));
    setCurrentCache({});
  }

  /**
   * @description 设置对应类别的缓存值
   * @param category 类别
   * @param key 缓存值 Key 名
   */
  const setCache = (category: string, key: string, value: any) => {
    const cache = localStorage.getItem(category);
    const newCache = Object.assign(JSON.parse(cache || '{}'), { [key]: value });
    localStorage.setItem(category, JSON.stringify(newCache));
    setCurrentCache(newCache);
  }

  const cache = getCategory(category);

  const [ currentCache, setCurrentCache ] = useState<Record<string, any>>(cache);

  return {
    cache: currentCache,
    addCategory,
    removeCategory,
    getCategory,
    getCache,
    setCache,
    removeCache,
  };
}
